package com.hxd.charitysystem.ui.activity

import android.app.Activity
import android.content.Intent
import android.provider.MediaStore
import com.hjq.dialog.WaitDialog
import com.hxd.charitysystem.R
import com.hxd.charitysystem.base.common.MyActivity
import com.hxd.charitysystem.bean.NetBaseBean
import com.hxd.charitysystem.bean.UserInfoBean
import com.hxd.charitysystem.image.ImageLoader
import com.hxd.charitysystem.utils.L
import com.hxd.charitysystem.utils.ProjectUrl
import com.hxd.tabactivityfragment.util.GsonToBean
import com.hxd.tabactivityfragment.util.StaticClassUtil
import com.hxd.tabactivityfragment.util.ThreadUtil
import com.kongzue.dialog.v3.BottomMenu
import com.kongzue.dialog.v3.InputDialog
import com.kymjs.rxvolley.RxVolley
import com.kymjs.rxvolley.client.HttpCallback
import com.kymjs.rxvolley.client.HttpParams
import com.vondear.rxtool.RxSPTool
import de.hdodenhof.circleimageview.CircleImageView
import kotlinx.android.synthetic.main.activity_user.*
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File


class UserActivity : MyActivity() {

    private var userImage:String = ""
    private var userName:String = ""
    private var userGender:String = ""
    private var userDescribe:String = "这个人很懒，什么都没留下"
    private var userPhone:String = ""

    private var imagePath = ""
    private var imageFile:File? = null

    private val token by lazy { RxSPTool.getString(this, "token") }
    private val commitWaitDialog by lazy { WaitDialog.Builder(this).setMessage("正在保存...").show(); }
    private val imageWaitDialog by lazy { WaitDialog.Builder(this).setMessage("正在上传图片...").show(); }

    override fun getLayoutId(): Int {
        return R.layout.activity_user
    }

    override fun getTitleId(): Int {
        return R.id.tb_user_title
    }

    override fun initView() {

        /**
         * 用户头像
         */
        rl_photo_user.setOnClickListener {
            BottomMenu.show(this, arrayOf("拍照", "从相册选择")) { text, index ->
                when(index){
                    0 -> {
                        fromCamera()
                    }

                    1 -> {
                        fromAlbum()
                    }
                }

            }.title = "选择头像"
        }

        /**
         * 昵称
         */
        rl_name_user.setOnClickListener {
            InputDialog.show(this, "昵称", "请输入昵称", "确定", "取消")
                .setOnOkButtonClickListener { baseDialog, v, inputStr ->
                    tv_name_user.text = inputStr
                    false
                }
        }

        /**
         * 性别
         */
        rl_gender_user.setOnClickListener {
            BottomMenu.show(this, arrayOf("男", "女")) { text, index ->
                when(index){
                    0 -> {
                        tv_gender_user.text = "男"
                    }

                    1 -> {
                        tv_gender_user.text = "女"
                    }
                }
            }.title = "选择性别"
        }

        /**
         * 个人介绍
         */
        rl_describe_user.setOnClickListener {
            InputDialog.show(this, "个人介绍", "请输入个人介绍", "确定", "取消")
                .setOnOkButtonClickListener { baseDialog, v, inputStr ->
                    tv_describe_user.text = inputStr
                    false
                }
        }

        /**
         * 手机号码
         */
        rl_phone_user.setOnClickListener {
            InputDialog.show(this, "手机号码", "请输入手机号码", "确定", "取消")
                .setOnOkButtonClickListener { baseDialog, v, inputStr ->

                    tv_phoneNumber_user.text = inputStr
                    false
                }
        }

        /**
         * 保存按钮
         */
        btn_save_user.setOnClickListener {

            /**
             * 说明：此处存在一个BUG，不能根据图片获取图片路径，一旦用户不修改图片便保存，那么图片还是会用的原来的那个
             * 后期技能提升后再做修改
             */

            userName = tv_name_user.text.toString()
            userGender = tv_gender_user.text.toString()
            userPhone = tv_phoneNumber_user.text.toString()
            userDescribe = tv_describe_user.text.toString()

            val params = HttpParams()
            params.putHeaders("token", token)
            params.putHeaders("application", "x-www-form-urlencoded")
            params.put("sex", userGender)
            params.put("name", userName)
            params.put("phone", userPhone)
            params.put("desc", userDescribe)
            if(imageFile != null){
                updataImage(imageFile, params)
            }else{
                updataUserInfo(params)
            }

        }
    }

    override fun initData() {
    }

    /**
     * 加载用户信息
     */
    private fun loadData(){
        val params = HttpParams()
        params.putHeaders("token", token)
        ProjectUrl.getUserInfo(params, object: HttpCallback(){
            override fun onSuccess(t: String?) {
                val userInfo = GsonToBean.JsonToBean<UserInfoBean>(t)
                if(userInfo.status == 200){
                    ThreadUtil.runOnMainThread(Runnable {
                        if (userInfo.msg.headerUrl != null){
                            ImageLoader.loadCircleImage(iv_phone_user, ProjectUrl.getUserImage + userInfo.msg.headerUrl)
                        }
                        tv_name_user.text = userInfo.msg.name
                        tv_gender_user.text = userInfo.msg.sex
                        tv_describe_user.text = userInfo.msg.desc
                        tv_phoneNumber_user.text = userInfo.msg.phone
                    })
                }else{
                    L.i("UserActivi用户信息获取失败： mag: ${userInfo.msg}")
                }
            }

            override fun onFailure(errorNo: Int, strMsg: String?) {
                L.i(" errorNo : $errorNo, strMsg: $strMsg ")
            }
        })
    }

    /**
     * 从相机选择
     */
    private fun fromCamera(){
        toast("从相机选择")
    }

    /**
     * 从相册选择
     */
    private fun fromAlbum(){
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, StaticClassUtil.ALBUM_REQUEST_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //调用相册
        if (requestCode == StaticClassUtil.ALBUM_REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
            callAlbum(data, iv_phone_user)
        }
    }

    /**
     * 调用相册功能
     */
    fun callAlbum(data: Intent, imageView: CircleImageView){
        ThreadUtil.runOnMainThread(Runnable {
            val selectedImage = data.data
            val filePathColumns = arrayOf(MediaStore.Images.Media.DATA)
            val cursor = contentResolver.query(selectedImage, filePathColumns, null, null, null)
            cursor.moveToFirst()
            val columnIndex = cursor.getColumnIndex(filePathColumns[0])
            //文件路径
            imagePath = cursor.getString(columnIndex)
            //进行图片压缩
            Luban.with(this).load(imagePath).ignoreBy(100).setCompressListener(object : OnCompressListener {
                override fun onSuccess(file: File?) {
                    ImageLoader.loadCircleImage(imageView, file?.path)
                    userImage = file?.path!!
                    imageFile = file
                }


                //当压缩过程出现问题时调用
                override fun onError(e: Throwable?) {

                }

                //当压缩过程出现开始时
                override fun onStart() {
                }
            }).launch()
            cursor.close()
        })
    }

    /**
     * 更新用户信息
     */
    private fun updataUserInfo(params:HttpParams){
        commitWaitDialog
        RxVolley.post(ProjectUrl.userInfo, params,object : HttpCallback() {
            override fun onSuccess(result: String?) {
                val data = GsonToBean.JsonToBean<NetBaseBean<String>>(result)
                commitWaitDialog.dismiss()
                if(data.status == 200){
                    toast("保存成功")
                    loadData()
                }
            }

            override fun onFailure(errorNo: Int, strMsg: String?) {
                commitWaitDialog.dismiss()
                L.i("upData errorNo : $errorNo, strMsg: $strMsg ")
            }
        })
    }

    /**
     * 更新照片
     */
    private fun updataImage(file:File?, userParams:HttpParams){
        val params = HttpParams()
        params.putHeaders("token", token)
        params.put("image", file)
        imageWaitDialog
        RxVolley.post(ProjectUrl.userImage, params, object:HttpCallback(){
            override fun onSuccess(result: String?) {
                val data = GsonToBean.JsonToBean<NetBaseBean<String>>(result)
                imageWaitDialog.dismiss()
                if(data.status == 200){
                    toast("头像上传成功！")
                    updataUserInfo(userParams)
                }else{
                    toast(data.msg)
                    L.i("updataImage : ${data.msg}")
                }
            }

            override fun onFailure(errorNo: Int, strMsg: String?) {
                imageWaitDialog.dismiss()
                L.i("upDataImage errorNo : $errorNo, strMsg: $strMsg ")
            }
        })
    }

    override fun onResume() {
        super.onResume()
        loadData()
    }

}
